package com.example.sfxfxm.controller;


import com.example.sfxfxm.repository.FormDataRepository;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.BindingResult;
import com.example.sfxfxm.pojo.*;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class SfController {
    private static final String QR_CODE_IMAGE_PATH = "d:/qrcodes/";

    @Autowired
    private FormDataRepository formDataRepository;


    @GetMapping("/form")
    public String showForm(FormData formData) {
        return "form";
    }

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute FormData formData, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        if (bindingResult.hasErrors()) {
            return "form"; // 返回表单页面并显示错误信息
        }
        // 处理表单数据
        System.out.println("手机号: " + formData.getPhoneNumber());
        System.out.println("人数: " + formData.getNumberOfPeople());
        System.out.println("儿童人数: " + formData.getNumberOfChildren());
        System.out.println("收取费用: " + formData.getChargeAmount());

        formDataRepository.save(formData);
        // 添加成功消息
        redirectAttributes.addFlashAttribute("message", "表单已成功提交！");


        // 生成二维码
        String qrCodeContent = "http://192.168.50.34:8080/verify?phoneNumber=" + formData.getPhoneNumber();
        String qrCodeImageName = formData.getPhoneNumber() + ".png";
        String filePath = QR_CODE_IMAGE_PATH + qrCodeImageName;
        File file = new File(filePath);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            System.out.println(qrCodeContent);
            QRCode.from(qrCodeContent).to(ImageType.PNG).writeTo(fos);
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "生成二维码失败！");
            return "redirect:/form";
        }

        // 添加成功消息
        redirectAttributes.addFlashAttribute("formData", formData);
        redirectAttributes.addFlashAttribute("message", "表单已成功提交！");
        redirectAttributes.addFlashAttribute("qrCodeUrl", "/qrcodes/" + qrCodeImageName);
        return "redirect:/qrCodeDetail";
    }

    @GetMapping("/qrCodeDetail")
    public String showQrCodeDetail() {
        return "qrCodeDetail";
    }

    @GetMapping("/qrcodes/{filename}")
    public ResponseEntity<Resource> serveQrCode(@PathVariable String filename) {
        File file = new File(QR_CODE_IMAGE_PATH + filename);
        if (file.exists()) {
            Resource resource = new FileSystemResource(file);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .contentType(MediaType.IMAGE_PNG)
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }


    @GetMapping("/verificationForm")
    public String showVerificationForm(@RequestParam String phoneNumber, Model model) {
        FormData formData = formDataRepository.findByPhoneNumber(phoneNumber);
        boolean isVerified = false;
        if (formData == null) {
            model.addAttribute("message", "未找到对应的表单数据。");
            return "verificationResult";
        }
        if (formData.getSfhx() == 1) {
            isVerified = true;
            // 创建 SimpleDateFormat 对象并指定格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = sdf.format(formData.getHxtime());
            model.addAttribute("verificationTime", formattedDate);
        }
        model.addAttribute("formData", formData);
        model.addAttribute("isVerified", isVerified);

        model.addAttribute("formData", formData);
        return "verificationForm";
    }

    @PostMapping("/verify")
    public String verifyPhoneNumber(@RequestParam String phoneNumber, @RequestParam String password, RedirectAttributes redirectAttributes) {
        FormData existingFormData = formDataRepository.findByPhoneNumber(phoneNumber);
        if (existingFormData == null) {
            redirectAttributes.addFlashAttribute("message", "未找到对应的表单数据。");
            return "redirect:/verificationForm?phoneNumber=" + phoneNumber;
        }

        // 验证固定的密码 "1234"
        if (!"1234".equals(password)) {
            redirectAttributes.addFlashAttribute("message", "密码错误。");
            return "redirect:/verificationForm?phoneNumber=" + phoneNumber;
        }

        // 核销操作：将 sfhx 字段设置为 1
        existingFormData.setSfhx(1);
        existingFormData.setHxtime(new Date());
        formDataRepository.save(existingFormData);

        redirectAttributes.addFlashAttribute("message", "表单已成功核销！");
        return "redirect:/verificationResult?phoneNumber=" + phoneNumber;
    }

    @GetMapping("/verificationResult")
    public String showVerificationResult(@RequestParam String phoneNumber, Model model) {
        FormData formData = formDataRepository.findByPhoneNumber(phoneNumber);
        if (formData == null) {
            model.addAttribute("message", "未找到对应的表单数据。");
            return "verificationResult";
        }
        model.addAttribute("formData", formData);
        return "verificationResult";
    }
}
